<?php
/**
 * 数据导入
 * @author jianhui
 *
 */
class Import extends MY_Controller{
    var $navbar = array();
    function Import(){
        parent::MY_Controller();
        if (!$this->auth->isImport()){
            showError('您无此页面操作权限','/');
        }
        $this->navbarFocus = 'AdminProType_index';
        $this->load->model('sellpointModel');
        //面包屑
        $this->viewData['breadcrumb'][] = array('url'=>printUrl('Import', 'index'),'title'=>'数据导入');
        //标签菜单
        $this->navbar = array(
            array('title'=>'首页','url'=>printUrl('Import','index'),'focusTag'=>'index'),
            array('title'=>'周数据','url'=>printUrl('Import','reachWeek'),'focusTag'=>'reachWeek'),
            array('title'=>'来店量达成标准进度','url'=>printUrl('Import','reachStandard'),'focusTag'=>'reachStandard'),
            array('title'=>'双月来店量目标','url'=>printUrl('Import','reachTimeUnit'),'focusTag'=>'reachTimeUnit'),
        );
        $this->viewData['focusTag'] = $this->input->get('m') ? $this->input->get('m') : 'index';
    }
    /**
     * 列表
     */
    function index(){
        //年
        $year = $this->input->get('year');
        $year || $year = $this->config->item('nowYear');
        $this->viewData['year'] = $year;
        $this->load->view('Import/index', $this->viewData);
    }
    /**
     * 来店量达成标准进度
     */
    function reachStandard(){
        $this->load->model('configModel');
        $key = 'reachStandard';
        if ($_POST){
            $reachStandard = $this->input->post('reachStandard');
            $this->configModel->saveConfigData($key, $reachStandard);
            showSuccess('保存成功', printUrl('Import', 'reachStandard'));
        }else{
            $this->viewData['reachStandard'] = $this->configModel->getConfigData($key);
            $this->load->view('Import/reachStandard', $this->viewData);
        }
    }
    /**
     * 导入周数据列表
     */
    function reachWeek(){
        $this->load->model('reachWeekModel');
        $where = array();
        //年
        $year = $this->input->get('year');
        $year || $year = $this->config->item('nowYear');
        $where['year'] = $year;
        $this->viewData['year'] = $year;
        //时间段
        $timeUnit = (int)$this->input->get('timeUnit');
        $timeUnit && $where['timeUnit'] = $timeUnit;
        $this->viewData['timeUnit'] = $timeUnit;
        //周
        $weekNum = (int)$this->input->get('weekNum');
        $weekNum && $where['weekNum'] = $weekNum;
        $this->viewData['weekNum'] = $weekNum;
        //关键字
        $keyword = $this->input->get('keyword');
        $keyword && $where['storeName'] = array('like',$keyword);
        $this->viewData['keyword'] = $keyword;
        //载入模型
        $count = $this->reachWeekModel->getCount($where);
        //分页
        $this->load->library('pagination');
        $getParam = $_GET;
        unset($getParam['c'], $getParam['m'], $getParam['page']);
        $config['base_url'] = printUrl($_GET['c'], $_GET['m'], $getParam);
        $config['total_rows'] = $count;
        $this->pagination->initialize($config);
        $this->viewData['pager'] = $this->pagination->create_links();
        $page = (int)$this->input->get('page');
        $limit = $this->pagination->per_page;
        $this->viewData['list'] = $this->reachWeekModel->getNewList($where, $limit, $page, '', 'id desc');
        $this->viewData['typeName'] = '周数据';
        $this->load->view('Import/reachWeek', $this->viewData);
    }
    /**
     * 周数据导入
     * @return boolean
     */
    function reachWeekAdd(){
        if ($_POST){
            $year = (int)$this->input->post('year');
            $year || showError('请选择年份');
            $timeUnit = (int)$this->input->post('timeUnit');
            $timeUnit || showError('请选择双月');
            $weekNum = (int)$this->input->post('weekNum');
            $weekNum || showError('请选择所属周');
            //上传文件
            $fileData = $this->upload();
            $fullPath = $fileData['full_path'];
            $handle = fopen ($fullPath, "r");
            $i = 0; $ok = 0; $err = 0;
            $errorSellpoint = array();
            //载入来店达成周版模型
            $this->load->model('reachWeekModel');
            $this->load->model('reachTimeUnitModel');
            while ($item = fgetcsv($handle, 10000, ",")){
                if($i==0){$i++;continue;}//跳过第一行
                $coding = $item[5];
                $storeData = $this->sellpointModel->getNewData(array('Coding'=>$coding, 'SpState_sys'=>1,'isOpen'=>1));
                if (!$storeData){
                    $err ++;
                    $errorSellpoint[] = "【".gbk2utf8($item[4])."】的编码【".$coding."】错误";
                    continue;
                }
                $where = array(
                    'storeId' => (int)$storeData['userId'],
                    'timeUnit' => (int)$timeUnit,
                    'weekNum' => $weekNum,
                    'year' => (int)$year,
                );
                $data = array(
                    'coding' => $storeData['coding'],
                    'storeName' => $storeData['storeName'],
                    'comeStoreActual' => (float)$item[6],//来店量实际
                    'pickCarActual' => (float)$item[7],//提车实际
                    'pickCarRate' => (float)$item[8],//提车达成(%)
                    'deliveryActual' => (float)$item[9],//交车实际
                    'deliveryRate' => (float)$item[10],//交车达成(%)
                    'createTime' => time()
                );
                //双月ID
                $reachTimeUnitId = $this->reachTimeUnitModel->initData(
                    array('storeId'=>$where['storeId'],'timeUnit'=>$where['timeUnit'],'year'=>$where['year']),
                    array('coding'=>$storeData['coding'],'storeName'=>$storeData['storeName'])
                );
                $where['reachTimeUnitId'] = $reachTimeUnitId;
                $id = $this->reachWeekModel->upset($where, $data);
                if ($id){
                    $this->reachWeekModel->updateMoney($id);
                    $ok ++;
                    //后续处理
                }else{
                    $err ++;
                }
                usleep(500);
            }
            showSuccess('导入完成：（成功条数：'.$ok.',失败条数：'.$err.'）'.($errorSellpoint ? "<br>".implode('<br>',$errorSellpoint):''), '', $errorSellpoint?120:3);
        }else{
            //年
            $year = $this->input->get('year');
            $year || $year = $this->config->item('nowYear');
            $this->viewData['year'] = $year;
            //时段
            $timeUnit = $this->input->get('timeUnit');
            $this->viewData['timeUnit'] = $timeUnit;
            //周数
            $weekNum = $this->input->get('weekNum');
            $this->viewData['weekNum'] = $weekNum;
            
            $this->viewData['templateFile'] = 'public/template/'.'reachWeek.zip';
            $this->load->view('Import/reachWeekAdd', $this->viewData);
        }
    }
    /**
     * 双月来店量目标
     */
    function reachTimeUnit(){
        $this->load->model('reachTimeUnitModel');
        $where = array();
        //年
        $year = $this->input->get('year');
        $year || $year = $this->config->item('nowYear');
        $where['year'] = $year;
        $this->viewData['year'] = $year;
        //时间段
        $timeUnit = (int)$this->input->get('timeUnit');
        $timeUnit && $where['timeUnit'] = $timeUnit;;
        $this->viewData['timeUnit'] = $timeUnit;
        //关键字
        $keyword = $this->input->get('keyword');
        $keyword && $where['storeName'] = array('like',$keyword);
        $this->viewData['keyword'] = $keyword;
        //载入模型
        $count = $this->reachTimeUnitModel->getCount($where);
        //分页
        $this->load->library('pagination');
        $getParam = $_GET;
        unset($getParam['c'], $getParam['m'], $getParam['page']);
        $config['base_url'] = printUrl($_GET['c'], $_GET['m'], $getParam);
        $config['total_rows'] = $count;
        $this->pagination->initialize($config);
        $this->viewData['pager'] = $this->pagination->create_links();
        $page = (int)$this->input->get('page');
        $limit = $this->pagination->per_page;
        $this->viewData['list'] = $this->reachTimeUnitModel->getNewList($where, $limit, $page, '', 'id desc');
        $this->viewData['typeName'] = '双月来店量目标';
        $this->load->view('Import/reachTimeUnit', $this->viewData);
    }
    /**
     * 双月来店量目标导入
     */
    function reachTimeUnitAdd(){
        if ($_POST){
            $year = (int)$this->input->post('year');
            $year || showError('请选择年份');
            $timeUnit = (int)$this->input->post('timeUnit');
            $timeUnit || showError('请选择双月');
            //上传文件
            $fileData = $this->upload();
            $fullPath = $fileData['full_path'];
            $handle = fopen ($fullPath, "r");
            $i = 0; $ok = 0; $err = 0;
            $errorSellpoint = array();
            //载入来店达成周版模型
            $this->load->model('reachWeekModel');
            $this->load->model('reachTimeUnitModel');
            while ($item = fgetcsv($handle, 10000, ",")){
                if($i==0){$i++;continue;}//跳过第一行
                $coding = $item[5];
                $storeData = $this->sellpointModel->getNewData(array('Coding'=>$coding, 'SpState_sys'=>1,'isOpen'=>1));
                if (!$storeData){
                    $err ++;
                    $errorSellpoint[] = "【".gbk2utf8($item[4])."】的编码【".$coding."】错误";
                    continue;
                }
                $where = array(
                    'storeId' => (int)$storeData['userId'],
                    'timeUnit' => (int)$timeUnit,
                    'year' => (int)$year,
                );
                $data = array(
                    'coding' => $storeData['coding'],
                    'storeName' => $storeData['storeName'],
                    'comeStoreTarget' => (float)$item[6],//来店目标
                    'updateTime' => time()
                );
                $id = $this->reachTimeUnitModel->upset($where, $data);
                if ($id){
                    $weekList = $this->reachWeekModel->getList(array('reachTimeUnitId'=>$id));
                    foreach ($weekList as $v){
                        $this->reachWeekModel->updateMoney($v['id']);
                    }
                    $ok ++;
                    //后续处理
                }else{
                    $err ++;
                }
                usleep(500);
            }
            showSuccess('导入完成：（成功条数：'.$ok.',失败条数：'.$err.'）'.($errorSellpoint ? "<br>".implode('<br>',$errorSellpoint):''), '', $errorSellpoint?120:3);
        }else{
            //年
            $year = $this->input->get('year');
            $year || $year = $this->config->item('nowYear');
            $this->viewData['year'] = $year;
            //时段
            $timeUnit = $this->input->get('timeUnit');
            $this->viewData['timeUnit'] = $timeUnit;
    
            $this->viewData['templateFile'] = 'public/template/'.'reachTimeUnit.zip';
            $this->load->view('Import/reachTimeUnitAdd', $this->viewData);
        }
    }
    /**
     * 上传文件
     * @return array
     */
    function upload(){
        //允许上传文件格式
        $config['allowed_types'] = 'csv';
        $extPath = date('Ymd');//子目录
        //上传目录
        $config['upload_path'] = '../upload/'. $extPath .'/';
        //网站目录
        $webPath = substr($config['upload_path'], 2);
        //判断上传目录是否存在，不存在则创建
        if (!is_dir($config['upload_path'])){
            mkdir($config['upload_path'],0777);
        }
        //是否重命名
        $config['encrypt_name'] = TRUE;
        $this->load->library('upload', $config);
        if ( ! $this->upload->do_upload('inputFile'))
        {
            $error = $this->upload->display_errors('','');
            showError($error);
        } else {
            $data = $this->upload->data();
            return $data;
        }
    }
}